package com.hskn.hss.module.kfkanalyse.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.alarmcar.entity.AlarmCar;
import com.hskn.hss.module.alarmcar.mapper.AlarmCarMapper;
import com.hskn.hss.module.alarmsheshi.entity.AlarmSheshi;
import com.hskn.hss.module.alarmsheshi.mapper.AlarmSheshiMapper;
import com.hskn.hss.module.carviolation.entity.CarViolation;
import com.hskn.hss.module.carviolation.service.ICarViolationService;
import com.hskn.hss.module.dlbjviolation.service.IDlbjViolationService;
import com.hskn.hss.module.kfkanalyse.entity.vo.car.WorkPlan;
import com.hskn.hss.module.kfkanalyse.entity.vo.car.WorkRuleItem;
import com.hskn.hss.module.kfkanalyse.mapper.KfkAnalyseMapper;
import com.hskn.hss.module.kfkanalyse.service.IkfkAnalyseService;
import com.hskn.hss.module.kfkbadge.mapper.KfkbadgeMapper;
import com.hskn.hss.module.kfkcarlocation.entity.KfkCarLocation;
import com.hskn.hss.module.kfkcarlocation.mapper.KfkCarLocationMapper;
import com.hskn.hss.module.kfkdtu.entity.KfkDtu;
import com.hskn.hss.module.kfkinterphone.entity.KfkInterphone;
import com.hskn.hss.module.kfkinterphone.mapper.KfkInterphoneMapper;
import com.hskn.hss.module.kfkworkcard.entity.KfkWorkCard;
import com.hskn.hss.module.kfkworkcard.mapper.KfkWorkCardMapper;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.mapper.TlCarTypeMapper;
import com.hskn.hss.module.tlequip.entity.TlEquip;
import com.hskn.hss.module.tlequip.mapper.TlEquipMapper;
import com.hskn.hss.module.tlfacilities.entity.TlFacilities;
import com.hskn.hss.module.tlfacilities.mapper.TlFacilitiesMapper;
import com.hskn.hss.module.tlthreshold.entity.TlThreshold;
import com.hskn.hss.module.tlthreshold.mapper.TlThresholdMapper;
import com.hskn.hss.utils.AlarmUtils;
import com.hskn.hss.utils.AttributeUtils;
import com.hskn.hss.utils.LocationUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.redis.RedisUtil;
import com.hskn.hss.utils.redis.key.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-25
 */
@Slf4j
@Service
public class KfkAnalyseServiceImpl implements IkfkAnalyseService {

    @Autowired
    TlEquipMapper tlEquipMapper;

    @Autowired
    TlFacilitiesMapper tlFacilitiesMapper;

    @Autowired
    TlThresholdMapper tlThresholdMapper;

    @Autowired
    AlarmSheshiMapper alarmSheshiMapper;

    @Autowired
    KfkCarLocationMapper kfkCarLocationMapper;

    @Autowired
    KfkInterphoneMapper kfkInterphoneMapper;

    @Autowired
    KfkWorkCardMapper kfkWorkCardMapper;

    @Autowired
    TlCarMapper tlCarMapper;

    @Autowired
    TlCarTypeMapper tlCarTypeMapper;

    @Autowired
    ITlCarService tlCarService;

    @Autowired
    AlarmCarMapper alarmCarMapper;

    @Autowired
    AlarmUtils alarmUtils;


    @Autowired
    IDlbjViolationService dlbjViolationService;


    @Autowired
    KfkAnalyseMapper kfkAnalyseMapper;

    @Autowired
    ICarViolationService carViolationService;

    @Autowired
    KfkbadgeMapper kfkbadgeMapper;

    @Autowired
    LocationUtils locationUtil;

    public void KfkDtuAnalyse(KfkDtu kfkDtu) {
        String eqpnum = kfkDtu.getEqpnum();
        String category = kfkDtu.getCategory();
        String value = kfkDtu.getValue();
        Date time = kfkDtu.getDeviceTime();

        QueryWrapper<TlEquip> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlEquip::getEquipcode, eqpnum);
        TlEquip tlEquip = tlEquipMapper.selectOne(queryWrapper);
        String objid = tlEquip.getBindobjid();

        TlFacilities tlFacilities = tlFacilitiesMapper.selectById(objid);
        String typeid = tlFacilities.getFacltypeid();

        TlThreshold threshold = new TlThreshold();

        if (category.equals("smoke")) {
            value = value.replace("ppm", "");
            QueryWrapper<TlThreshold> thqueryWrapper = new QueryWrapper<>();
            thqueryWrapper.lambda().eq(TlThreshold::getItemid, objid);
            thqueryWrapper.lambda().eq(TlThreshold::getSysname, "烟雾报警");
            threshold = tlThresholdMapper.selectOne(thqueryWrapper);

            if (threshold == null) {//如果根据itemid获取不到 就按type进行获取
                QueryWrapper<TlThreshold> thitemqueryWrapper = new QueryWrapper<>();
                thitemqueryWrapper.lambda().eq(TlThreshold::getFaclitypeid, typeid);
                thqueryWrapper.lambda().eq(TlThreshold::getSysname, "烟雾报警");
                threshold = tlThresholdMapper.selectOne(thitemqueryWrapper);
            }
        } else if (category.equals("ammonia")) {
            value = value.replace("ppm", "");
            QueryWrapper<TlThreshold> thqueryWrapper = new QueryWrapper<>();
            thqueryWrapper.lambda().eq(TlThreshold::getItemid, objid);
            thqueryWrapper.lambda().eq(TlThreshold::getSysname, "氨气报警");
            threshold = tlThresholdMapper.selectOne(thqueryWrapper);

            if (threshold == null) {//如果根据itemid获取不到 就按type进行获取
                QueryWrapper<TlThreshold> thitemqueryWrapper = new QueryWrapper<>();
                thitemqueryWrapper.lambda().eq(TlThreshold::getFaclitypeid, typeid);
                thqueryWrapper.lambda().eq(TlThreshold::getSysname, "氨气报警");
                threshold = tlThresholdMapper.selectOne(thitemqueryWrapper);
            }
        }
        String jsonstr = threshold.getThreshold();
        Map thvalue = JSONObject.parseObject(jsonstr, Map.class);
        Double remarkvlue = 0D;
        if (null != thvalue) {
            if (null != thvalue.get("ywnd")) {
                remarkvlue = Double.valueOf(String.valueOf(thvalue.get("ywnd")));
            } else if (null != thvalue.get("aqnd")) {
                remarkvlue = Double.valueOf(String.valueOf(thvalue.get("aqnd")));
            } else if (null != thvalue.get("lhqnd")) {
                remarkvlue = Double.valueOf(String.valueOf(thvalue.get("lhqnd")));
            }
        }
        Double kfkvalue = 0D;
        if (value.contains("%RH")) {
            kfkvalue = Double.valueOf(value.substring(0, 3));
        } else {
            if (!"".equals(value)) {
                kfkvalue = Double.valueOf(value);
            }
        }
        AlarmSheshi alarmSheshi = new AlarmSheshi();
        if (kfkvalue >= remarkvlue && null != tlFacilities && null != threshold) {
            alarmSheshi.setAlarmTime(time);
            alarmSheshi.setAlarmTypeId(threshold.getId());
            alarmSheshi.setAlarmTypeName(threshold.getSysname());
            alarmSheshi.setContent(threshold.getSysname() + ",浓度：" + value + "ppm");
            alarmSheshi.setAddress(tlFacilities.getFacladdrdetail());
            alarmSheshi.setDepId(tlFacilities.getFacldeptid());
            alarmSheshi.setDepName("");
            alarmSheshi.setLat(tlFacilities.getFacladdr().split(",")[0]);
            alarmSheshi.setLng(tlFacilities.getFacladdr().split(",")[1]);
            alarmSheshi.setSheshiId(tlFacilities.getId());
            alarmSheshi.setSheshiName(tlFacilities.getFaclname());
            alarmSheshiMapper.insert(alarmSheshi);
        }

    }

    /**
     * 分析车俩定位，
     *
     * @param kfkCarLocation
     */
    @Override
    public void KfkCarStayAnalyse(KfkCarLocation kfkCarLocation) throws ParseException {
        try {
            JSONObject json = new JSONObject();
            String key = kfkCarLocation.getEqpnum();
            String times = StringUtils.DateFormat(kfkCarLocation.getDeviceTime());
            String id = kfkCarLocation.getId();
            String workstatus = kfkCarLocation.getStatus(); // 开关状态：1开 0关
            float lat = (float) Math.round(Float.parseFloat(kfkCarLocation.getLat()) * 100) / 100;
            float lon = (float) Math.round(Float.parseFloat(kfkCarLocation.getLon()) * 100) / 100;
            Long staysecond = 0l;
            Long movesecond = 0l;
            Long worksecond = 0l;

            JSONObject latvalues = RedisUtil.get(CarMoveAndStayKey.token, key, JSONObject.class);
            if (null != latvalues) {
                float latlat = Float.parseFloat(String.valueOf(latvalues.get("lat")));
                float latlon = Float.parseFloat(String.valueOf(latvalues.get("lon")));
                Long latstaysecond = Long.valueOf(String.valueOf(latvalues.get("staysecond")));
                Long latmovesecond = Long.valueOf(String.valueOf(latvalues.get("movesecond")));
                String latid = String.valueOf(latvalues.get("id"));

                if (latlat == lat && latlon == lon) {
                    Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
                    staysecond = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
                    staysecond += latstaysecond;
                    if (latmovesecond > 0) {
                        KfkCarLocation kfkCarLocation1 = kfkCarLocationMapper.selectById(latid);
                        kfkCarLocation1.setIsstay("1");
                        kfkCarLocation1.setSecond(Math.toIntExact(latmovesecond)); //移动时长
                        kfkCarLocationMapper.updateById(kfkCarLocation1);
                    }
                } else if (latstaysecond > 0) {
                    KfkCarLocation kfkCarLocation1 = kfkCarLocationMapper.selectById(latid);
                    kfkCarLocation1.setIsstay("0");
                    kfkCarLocation1.setSecond(Math.toIntExact(latstaysecond)); //停留时长
                    kfkCarLocationMapper.updateById(kfkCarLocation1);
                } else {
                    Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
                    movesecond = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
                    movesecond += latmovesecond;
                    if (workstatus.equals("0")) {
                        worksecond = movesecond;
                        if (worksecond > 600) {
                            log.info("空驶报警" + worksecond);
                        }
                    }
                }
            }
            json.put("id", id);
            json.put("time", times);
            json.put("lat", lat);
            json.put("lon", lon);
            json.put("staysecond", staysecond);
            json.put("movesecond", movesecond);
            json.put("worksecond", worksecond);
            RedisUtil.set(CarMoveAndStayKey.token, key, json);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void KfkInterphoneStayAnalyse(KfkInterphone kfkInterphone) throws ParseException {
        try {
            JSONObject json = new JSONObject();
            String key = kfkInterphone.getEqpnum();
            String times = StringUtils.DateFormat(kfkInterphone.getDeviceTime());
            String id = kfkInterphone.getId();
            float lat = (float) Math.round(Float.parseFloat(kfkInterphone.getLat()) * 1000) / 1000;
            float lon = (float) Math.round(Float.parseFloat(kfkInterphone.getLon()) * 1000) / 1000;
            Long staysecond = 0l;
            Long movesecond = 0l;
            JSONObject latvalues = RedisUtil.get(InterphoneMoveAndStayKey.token, key, JSONObject.class);
            if (null != latvalues) {
                float latlat = Float.parseFloat(String.valueOf(latvalues.get("lat")));
                float latlon = Float.parseFloat(String.valueOf(latvalues.get("lon")));
                Long latstaysecond;
                Long latmovesecond;
                if (null != latvalues.get("staysecond")) {
                    latstaysecond = Long.valueOf(String.valueOf(latvalues.get("staysecond")));
                } else {
                    latstaysecond = 0l;
                }
                if (null != latvalues.get("staysecond")) {
                    latmovesecond = Long.valueOf(String.valueOf(latvalues.get("movesecond")));
                } else {
                    latmovesecond = 0l;
                }
                String latid = String.valueOf(latvalues.get("id"));

                if (latlat == lat && latlon == lon) {
                    Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
                    staysecond = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
                    staysecond += latstaysecond;
                    if (latmovesecond > 0) {
                        KfkInterphone kfkInterphone1 = kfkInterphoneMapper.selectById(latid);
                        kfkInterphone1.setIsstay("1");
                        kfkInterphone1.setSecond(Math.toIntExact(latmovesecond)); //移动时长
                        kfkInterphoneMapper.updateById(kfkInterphone1);
                    }

                } else if (latstaysecond > 0) {
                    KfkInterphone kfkInterphone1 = kfkInterphoneMapper.selectById(latid);
                    if (null != kfkInterphone1) {
                        kfkInterphone1.setIsstay("0");
                        kfkInterphone1.setSecond(Math.toIntExact(latstaysecond)); //停留时长
                        kfkInterphoneMapper.updateById(kfkInterphone1);
                    }
                } else {
                    Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
                    movesecond = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
                    movesecond += latmovesecond;
                }
            }
            json.put("id", id);
            json.put("time", times);
            json.put("lat", lat);
            json.put("lon", lon);
            json.put("staysecond", staysecond);
            json.put("movesecond", movesecond);
            RedisUtil.set(InterphoneMoveAndStayKey.token, key, json);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void KfkWorkcardStayAnalyse(KfkWorkCard kfkWorkCard) {
        try {
            JSONObject json = new JSONObject();
            String key = kfkWorkCard.getEqpnum();
            String times = StringUtils.DateFormat(kfkWorkCard.getDeviceTime());
            String id = kfkWorkCard.getId();
            String location = kfkWorkCard.getLocation();
            String[] locationArry = location.split(",");
            float lat = (float) Math.round(Float.parseFloat(locationArry[0]) * 1000) / 1000;
            float lon = (float) Math.round(Float.parseFloat(locationArry[1]) * 1000) / 1000;
            Long staysecond = 0l;
            Long movesecond = 0l;
            JSONObject latvalues = RedisUtil.get(WorkCardMoveAndStayKey.token, key, JSONObject.class);
            if (null != latvalues) {
                float latlat = Float.parseFloat(String.valueOf(latvalues.get("lat")));
                float latlon = Float.parseFloat(String.valueOf(latvalues.get("lon")));
                Long latstaysecond = Long.valueOf(String.valueOf(latvalues.get("staysecond")));
                Long latmovesecond = Long.valueOf(String.valueOf(latvalues.get("movesecond")));
                String latid = String.valueOf(latvalues.get("id"));

                if (latlat == lat && latlon == lon) {
                    Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
                    staysecond = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
                    staysecond += latstaysecond;
                    if (latmovesecond > 0) {
                        KfkWorkCard kfkWorkCard1 = kfkWorkCardMapper.selectById(latid);
                        kfkWorkCard1.setIsstay("1");
                        kfkWorkCard1.setSecond(Math.toIntExact(latmovesecond)); //移动时长
                        kfkWorkCardMapper.updateById(kfkWorkCard1);
                    }

                } else if (latstaysecond > 0) {
                    KfkWorkCard kfkWorkCard1 = kfkWorkCardMapper.selectById(latid);
                    kfkWorkCard1.setIsstay("0");
                    kfkWorkCard1.setSecond(Math.toIntExact(latstaysecond)); //停留时长
                    kfkWorkCardMapper.updateById(kfkWorkCard1);
                } else {
                    Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
                    movesecond = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
                    movesecond += latmovesecond;
                }
            }
            json.put("id", id);
            json.put("time", times);
            json.put("lat", lat);
            json.put("lon", lon);
            json.put("staysecond", staysecond);
            json.put("movesecond", movesecond);
            RedisUtil.set(WorkCardMoveAndStayKey.token, key, json);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void KfkCarSpeedAnalyse(KfkCarLocation kfkCarLocation) throws ParseException, HssException {
        try {
            JSONObject json = new JSONObject();
            String key = kfkCarLocation.getEqpnum();
            String times = StringUtils.DateFormat(kfkCarLocation.getDeviceTime());
            int speed = kfkCarLocation.getSpeed();
            Long second = 0l;

            JSONObject latvalues = RedisUtil.get(CarSpeedAndTimeKey.token, key, JSONObject.class);
            if (null != latvalues) {
                Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("times")));
                second = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
            }

            Double sppedvalue = Double.valueOf(kfkCarLocation.getSpeed());
            QueryWrapper<TlEquip> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TlEquip::getEquipcode, kfkCarLocation.getEqpnum());
            TlEquip tlEquip = tlEquipMapper.selectOne(queryWrapper);

            String objid = tlEquip.getBindobjid();
            JSONObject param = new JSONObject();
            param.put("id", objid);
            TlCar tlCar = tlCarService.getDetail(param);
            Map thvalue = alarmUtils.getCompare(kfkCarLocation.getEqpnum(), "超速");
            Double remarkvalue = Double.valueOf(String.valueOf(thvalue.get("xs")));
            String thresholdid = String.valueOf(thvalue.get("thresholdid"));
            String sysname = String.valueOf(thvalue.get("sysname"));
            if (sppedvalue > remarkvalue) {
                AlarmCar alarmCar = new AlarmCar();
                alarmCar.setCarId(tlCar.getId());
                alarmCar.setCarName(tlCar.getCarnumber());
                alarmCar.setDepId(tlCar.getCardeptid());
                alarmCar.setDepName(tlCar.getCardeptname());
                alarmCar.setLat(kfkCarLocation.getLat());
                alarmCar.setLng(kfkCarLocation.getLon());
                alarmCar.setCreateTime(new Date());
                /** 保存地址 **/
                String currentAddress = locationUtil.getAddress(kfkCarLocation.getLon(), kfkCarLocation.getLat());
                if (StringUtils.isNotEmpty(currentAddress)) {
                    alarmCar.setAddress(currentAddress);
                } else {
                    alarmCar.setAddress("");
                }
                alarmCar.setAlarmTime(kfkCarLocation.getDeviceTime());
                alarmCar.setAlarmTypeId(thresholdid);
                alarmCar.setAlarmTypeName(sysname);
                alarmCar.setContent(sysname + ",当前速度：" + kfkCarLocation.getSpeed() + "km/h");
                if (second >= 600 || second == 0) {
                    //根据carId查询type
                    TlCar tlCar2 = tlCarMapper.selectById(alarmCar.getCarId());
                    String typeId = "";
                    String typeName = "";
                    if (Objects.nonNull(tlCar2) && StringUtils.isNotEmpty(tlCar2.getCartypeid())) {
                        typeId = tlCar2.getCartypeid();
                        TlCarType tlCarType = tlCarTypeMapper.selectById(tlCar2.getCartypeid());
                        if (Objects.nonNull(tlCarType) && StringUtils.isNotEmpty(tlCarType.getTypename())) {
                            typeName = tlCarType.getTypename();
                        }
                    }
                    alarmCar.setCarTypeId(typeId);
                    alarmCar.setCarTypeName(typeName);

                    alarmCarMapper.insert(alarmCar);
                    json.put("speed", speed);
                    json.put("times", times);
                    RedisUtil.set(CarSpeedAndTimeKey.token, key, json);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

//    @Override
//    public void KfkCarOilAnalyse(KfkCarLocation kfkCarLocation) throws ParseException, HssException {
//        try {
//            JSONObject json = new JSONObject();
//            String key = kfkCarLocation.getEqpnum();
//            String times = StringUtils.DateFormat(kfkCarLocation.getDeviceTime());
//            Double oilvalue = kfkCarLocation.getOilmass();
//
//            QueryWrapper<TlEquip> queryWrapper = new QueryWrapper<>();
//            queryWrapper.lambda().eq(TlEquip::getEquipcode, kfkCarLocation.getEqpnum());
//            TlEquip tlEquip = tlEquipMapper.selectOne(queryWrapper);
//
//            String objid = tlEquip.getBindobjid();
//            JSONObject param = new JSONObject();
//            param.put("id", objid);
//            TlCar tlCar = tlCarService.getDetail(param);
//
//            Map thvalue = alarmUtils.getCompare(kfkCarLocation.getEqpnum(), "漏油");
////            int remarkvalue = Integer.valueOf(String.valueOf(thvalue.get("yxrcl"))); //获取对比 容错率
//            String thresholdid = String.valueOf(thvalue.get("thresholdid"));
//            String sysname = String.valueOf(thvalue.get("sysname"));
//
//            JSONObject latvalues = RedisUtil.get(CarOilKey.token, key, JSONObject.class);
//            if (null != latvalues) {
//                Double lastoil = Double.valueOf(String.valueOf(latvalues.get("oil")));
//                Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
//                Double compareval = lastoil - remarkvalue;
//                Long second = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
//                if (oilvalue <= compareval) {
//                    AlarmCar alarmCar = new AlarmCar();
//                    alarmCar.setCarId(tlCar.getId());
//                    alarmCar.setCarName(tlCar.getCarnumber());
//                    alarmCar.setDepId(tlCar.getCardeptid());
//                    alarmCar.setDepName(tlCar.getCardeptname());
//                    alarmCar.setLat(kfkCarLocation.getLat());
//                    alarmCar.setLng(kfkCarLocation.getLon());
//                    alarmCar.setCreateTime(new Date());
//                    /** 保存地址 **/
//                    String currentAddress = locationUtil.getAddress(kfkCarLocation.getLon(), kfkCarLocation.getLat());
//                    if (StringUtils.isNotEmpty(currentAddress)){
//                        alarmCar.setAddress(currentAddress);
//                    } else {
//                        alarmCar.setAddress("");
//                    }
//                    alarmCar.setAlarmTime(kfkCarLocation.getDeviceTime());
//                    alarmCar.setAlarmTypeId(thresholdid);
//                    alarmCar.setAlarmTypeName(sysname);
//                    alarmCar.setContent("燃油下降过快：" + second + "秒内，下降超过" + remarkvalue + "%，请注意。"
//                            + "上次燃油剩余量：(时间：" + String.valueOf(latvalues.get("time")) + "油量：" + lastoil
//                            + ") 本次燃油剩余量：(时间：" + times + "油量：" + oilvalue + ")");
//
//                    //根据carId查询type
//                    TlCar tlCar2 = tlCarMapper.selectById(alarmCar.getCarId());
//                    String typeId = "";
//                    String typeName = "";
//                    if (Objects.nonNull(tlCar2) && StringUtils.isNotEmpty(tlCar2.getCartypeid())) {
//                        typeId = tlCar2.getCartypeid();
//                        TlCarType tlCarType = tlCarTypeMapper.selectById(tlCar2.getCartypeid());
//                        if (Objects.nonNull(tlCarType) && StringUtils.isNotEmpty(tlCarType.getTypename())) {
//                            typeName = tlCarType.getTypename();
//                        }
//                    }
//                    alarmCar.setCarTypeId(typeId);
//                    alarmCar.setCarTypeName(typeName);
//                    alarmCarMapper.insert(alarmCar);
//                }
//            }
//            json.put("time", times);
//            json.put("oil", oilvalue);
//            RedisUtil.set(CarOilKey.token, key, json);
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//        }
//    }

    @Override
    public void KfkCarDriverAlarmAnalyse(KfkCarLocation kfkCarLocation) throws ParseException, HssException {
        try {
            JSONObject json = new JSONObject();
            String key = kfkCarLocation.getEqpnum();
            String times = StringUtils.DateFormat(kfkCarLocation.getDeviceTime());
            String id = kfkCarLocation.getId();
            float lat = (float) Math.round(Float.parseFloat(kfkCarLocation.getLat()) * 100) / 100;
            float lon = (float) Math.round(Float.parseFloat(kfkCarLocation.getLon()) * 100) / 100;
            Long staysecond = 0l;
            Long movesecond = 0l;
            int isalarm = 0;

            JSONObject latvalues = RedisUtil.get(CarMoveAndStayAndAlarmKey.token, key, JSONObject.class);
            if (null != latvalues) {
                float latlat = Float.parseFloat(String.valueOf(latvalues.get("lat")));
                float latlon = Float.parseFloat(String.valueOf(latvalues.get("lon")));
                Long latstaysecond = Long.valueOf(String.valueOf(latvalues.get("staysecond")));
                Long latmovesecond = Long.valueOf(String.valueOf(latvalues.get("movesecond")));
                isalarm = Integer.valueOf(String.valueOf(latvalues.get("isalarm")));

                if (latlat == lat && latlon == lon) {
                    Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
                    staysecond = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
                    staysecond += latstaysecond;
                    movesecond = latmovesecond;
                } else {
                    Date lattime = StringUtils.StringToDate(String.valueOf(latvalues.get("time")));
                    movesecond = (StringUtils.StringToDate(times).getTime() - lattime.getTime()) / 1000;
                    movesecond += latmovesecond;
                    staysecond = latstaysecond;
                }

                Map thvalue = alarmUtils.getCompare(kfkCarLocation.getEqpnum(), "疲劳驾驶");
                Long xx = Long.valueOf(String.valueOf(thvalue.get("xx"))) * 60;
                Long js = Long.valueOf(String.valueOf(thvalue.get("js"))) * 60;
                String thresholdid = String.valueOf(thvalue.get("thresholdid"));
                String sysname = String.valueOf(thvalue.get("sysname"));
                if (staysecond >= xx) {
                    movesecond = 0l;
                    staysecond = 0l;
                    isalarm = 0;
                } else if (movesecond >= js && staysecond < xx) {
                    QueryWrapper<TlEquip> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(TlEquip::getEquipcode, kfkCarLocation.getEqpnum());
                    TlEquip tlEquip = tlEquipMapper.selectOne(queryWrapper);
                    String objid = tlEquip.getBindobjid();
                    JSONObject param = new JSONObject();
                    param.put("id", objid);
                    TlCar tlCar = tlCarService.getDetail(param);
                    String[] location = tlCar.getAddr().split(",");
                    AlarmCar alarmCar = new AlarmCar();
                    alarmCar.setCarId(tlCar.getId());
                    alarmCar.setCarName(tlCar.getCarnumber());
                    alarmCar.setDepId(tlCar.getCardeptid());
                    alarmCar.setDepName(tlCar.getCardeptname());
                    alarmCar.setLat(location[1]);
                    alarmCar.setLng(location[0]);
                    alarmCar.setCreateTime(new Date());
                    /** 保存地址 **/
                    String currentAddress = locationUtil.getAddress(location[0], location[1]);
                    if (StringUtils.isNotEmpty(currentAddress)) {
                        alarmCar.setAddress(currentAddress);
                    } else {
                        alarmCar.setAddress("");
                    }
                    alarmCar.setAlarmTime(new Date());
                    alarmCar.setAlarmTypeId(thresholdid);
                    alarmCar.setAlarmTypeName(sysname);
                    alarmCar.setContent("疲劳驾驶报警：已驾驶" + (movesecond / 60) + "分钟，休息" + (staysecond / 60) + "分钟");
                    if (isalarm < 1) {

                        //根据carId查询type
                        TlCar tlCar2 = tlCarMapper.selectById(alarmCar.getCarId());
                        String typeId = "";
                        String typeName = "";
                        if (Objects.nonNull(tlCar2) && StringUtils.isNotEmpty(tlCar2.getCartypeid())) {
                            typeId = tlCar2.getCartypeid();
                            TlCarType tlCarType = tlCarTypeMapper.selectById(tlCar2.getCartypeid());
                            if (Objects.nonNull(tlCarType) && StringUtils.isNotEmpty(tlCarType.getTypename())) {
                                typeName = tlCarType.getTypename();
                            }
                        }
                        alarmCar.setCarTypeId(typeId);
                        alarmCar.setCarTypeName(typeName);
                        alarmCarMapper.insert(alarmCar);
                        isalarm = 1;
                    }
                }
            }

            json.put("id", id);
            json.put("time", times);
            json.put("lat", lat);
            json.put("lon", lon);
            json.put("staysecond", staysecond);
            json.put("movesecond", movesecond);
            json.put("isalarm", isalarm);
            RedisUtil.set(CarMoveAndStayAndAlarmKey.token, key, json);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void personQuitJob() {

    }

    @Override
    public void personGathering() {

    }

    @Override
    public void personStay() {

    }

    @Override
    public void carViolation(TlCar car, KfkCarLocation kfkCarLocation) {
        JSONObject params = new JSONObject();
        params.put("carId", car.getId());
        params.put("date", kfkCarLocation.getDeviceTime());
        // TODO: 2021/6/25 一辆车作业周期是2天或多天，轮换在不同的网格工作的情况
        // TODO: 2021/6/25 后续优化这里查询只能查出一个，管理后台添加作业计划的时候判断一辆车日计划不能冲突

        String date = String.valueOf(params.get("date"));
        if (StringUtils.isNotEmpty(date)) {
            String startDate = AttributeUtils.timeCompletion(date, 's');
            String endDate = AttributeUtils.timeCompletion(date, 'e');

            params.put("startDate", startDate);
            params.put("endDate", endDate);
        }

        List<WorkPlan> workPlans = kfkAnalyseMapper.getCarViolationAnalyseBasics(params);
        if (workPlans.size() == 1) {
            for (WorkPlan plan : workPlans) {
                if (plan.getWorkRuleItems().size() > 0) {
                    for (WorkRuleItem ruleItem : plan.getWorkRuleItems()) {
                        try {
                            switch (ruleItem.getRuleItemName()) {
                                case "车辆空驶":
                                    carInvalidDrive();
                                    break;
                                case "车辆停留":
                                    carStay();
                                    break;
                                case "作业遗留":
                                    carWorkLeaveOver();
                                    break;
                                case "速度限制":
                                    JSONObject ruleContent = JSONObject.parseObject(ruleItem.getRuleItemContent());
                                    Integer zd = ruleContent.getInteger("zd");
                                    if (kfkCarLocation.getSpeed() > zd) {
                                        CarViolation carViolation = new CarViolation(car.getId(), car.getCarnumber(),
                                                car.getCartypeid(), null, car.getDeptid(), null, ruleItem.getRuleItemId(),
                                                ruleItem.getRuleItemName(), kfkCarLocation.getDeviceTime(), kfkCarLocation.getLon(),
                                                kfkCarLocation.getLat(), null,
                                                "车辆" + car.getCarnumber() + "作业中行驶异常，行驶速度为：" + kfkCarLocation.getSpeed() + "km/h",
                                                plan.getWorkGrid().getGridId(), plan.getModule());
                                        carViolationService.save(carViolation);
                                    }
                                    break;
                                case "水量监测":
                                    carWaterMonitor();
                                    break;
                                case "油量监测":
                                    carOilMonitor();
                                    break;
                                case "离岗":
                                    carQuitJob();
                                    break;
                                case "晚到":
                                    carLate();
                                    break;
                                case "未到岗":
                                    carHooky();
                                    break;
                                case "超时未完成":
                                    carTimeoutUndone();
                                    break;
                                case "非法倾倒":
                                    carIllegalDump();
                                    break;
                                default:
                                    break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error("报错ERROR", e);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void carStay() {

    }

    @Override
    public void carInvalidDrive() {

    }

    @Override
    public void carWorkLeaveOver() {

    }

    @Override
    public void carSpeedLimit(String carId, WorkRuleItem rule, Integer speed) {

    }

    @Override
    public void carWaterMonitor() {

    }

    @Override
    public void carOilMonitor() {

    }

    @Override
    public void carQuitJob() {

    }

    @Override
    public void carLate() {

    }

    @Override
    public void carHooky() {

    }

    @Override
    public void carTimeoutUndone() {

    }

    @Override
    public void carIllegalDump() {

    }

    @Override
    public void personAttendance() {

    }

}
